<template>
  <div class="data-table-enhanced">
    <!-- 搜索工具栏 -->
    <div v-if="showSearchToolbar" class="search-toolbar">
      <t-input
        v-model="searchKeyword"
        :placeholder="searchPlaceholder"
        clearable
        @enter="handleSearch"
      >
        <template #suffix>
          <t-button theme="primary" @click="handleSearch">
            <template #icon>
              <t-icon name="search" />
            </template>
            搜索
          </t-button>
        </template>
      </t-input>
      
      <!-- 高级搜索按钮 -->
      <t-button v-if="showAdvancedSearch" theme="default" @click="toggleAdvancedSearch">
        <template #icon>
          <t-icon :name="showAdvancedSearchPanel ? 'caret-up' : 'caret-down'" />
        </template>
        高级搜索
      </t-button>
      
      <!-- 自定义搜索插槽 -->
      <slot name="search-toolbar" />
    </div>

    <!-- 高级搜索面板 -->
    <div v-if="showAdvancedSearch && showAdvancedSearchPanel" class="advanced-search-panel">
      <t-form :data="searchForm" :layout="advancedSearchLayout">
        <t-row :gutter="[16, 16]">
          <t-col v-for="field in advancedSearchFields" :key="field.name" :span="field.span || 6">
            <t-form-item :label="field.label" :name="field.name">
              <component
                :is="getFieldComponent(field.type)"
                v-model="searchForm[field.name]"
                :placeholder="field.placeholder"
                :options="field.options"
                clearable
              />
            </t-form-item>
          </t-col>
        </t-row>
        
        <div class="search-actions">
          <t-button theme="primary" @click="handleAdvancedSearch">搜索</t-button>
          <t-button theme="default" @click="handleResetSearch">重置</t-button>
        </div>
      </t-form>
    </div>

    <!-- 基础表格组件 -->
    <DataTable
      ref="tableRef"
      :data="filteredData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :selected-row-keys="selectedRowKeys"
      :show-toolbar="showToolbar"
      :show-add-button="showAddButton"
      :show-delete-button="showDeleteButton"
      :show-export-button="showExportButton"
      :show-actions="showActions"
      :actions="actions"
      :add-button-text="addButtonText"
      :delete-button-text="deleteButtonText"
      :export-button-text="exportButtonText"
      @select-change="handleSelectChange"
      @page-change="handlePageChange"
      @add="handleAdd"
      @delete="handleDelete"
      @export="handleExport"
      @action-click="handleActionClick"
    >
      <!-- 透传所有插槽 -->
      <template v-for="(_, slotName) in $slots" #[slotName]="slotProps">
        <slot :name="slotName" v-bind="slotProps" />
      </template>
      
      <!-- 自定义工具栏插槽 -->
      <template #toolbar>
        <slot name="toolbar" />
      </template>
    </DataTable>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import DataTable from './DataTable.vue'

// 高级搜索字段配置
interface AdvancedSearchField {
  name: string
  label: string
  type: 'input' | 'select' | 'date' | 'date-range'
  placeholder?: string
  options?: Array<{ label: string; value: any }>
  span?: number
}

// Props
interface Props {
  // 数据相关
  data: any[]
  columns: any[]
  loading?: boolean
  
  // 搜索相关
  showSearchToolbar?: boolean
  searchPlaceholder?: string
  showAdvancedSearch?: boolean
  advancedSearchFields?: AdvancedSearchField[]
  advancedSearchLayout?: 'vertical' | 'horizontal'
  
  // 分页相关
  pagination?: {
    current: number
    pageSize: number
    total: number
  }
  
  // 选择相关
  selectedRowKeys?: (string | number)[]
  
  // 工具栏配置
  showToolbar?: boolean
  showAddButton?: boolean
  showDeleteButton?: boolean
  showExportButton?: boolean
  showActions?: boolean
  actions?: any[]
  
  // 按钮文本
  addButtonText?: string
  deleteButtonText?: string
  exportButtonText?: string
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  showSearchToolbar: true,
  searchPlaceholder: '请输入关键词搜索',
  showAdvancedSearch: false,
  advancedSearchFields: () => [],
  advancedSearchLayout: 'horizontal',
  pagination: () => ({
    current: 1,
    pageSize: 10,
    total: 0
  }),
  selectedRowKeys: () => [],
  showToolbar: true,
  showAddButton: false,
  showDeleteButton: false,
  showExportButton: false,
  showActions: false,
  actions: () => [],
  addButtonText: '新增',
  deleteButtonText: '删除',
  exportButtonText: '导出'
})

// 响应式数据
const searchKeyword = ref('')
const showAdvancedSearchPanel = ref(false)
const searchForm = ref({})

// 初始化搜索表单
const initSearchForm = () => {
  const form: Record<string, any> = {}
  props.advancedSearchFields.forEach(field => {
    form[field.name] = ''
  })
  searchForm.value = form
}

// 初始化
initSearchForm()

// 计算属性
const filteredData = computed(() => {
  if (!searchKeyword.value && Object.values(searchForm.value).every(val => !val)) {
    return props.data
  }
  
  return props.data.filter(item => {
    // 关键词搜索
    const keywordMatch = !searchKeyword.value || 
      Object.values(item).some(val => 
        String(val).toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    
    // 高级搜索
    const advancedMatch = Object.entries(searchForm.value).every(([key, value]) => {
      if (!value) return true
      return String(item[key]).includes(String(value))
    })
    
    return keywordMatch && advancedMatch
  })
})

// 方法
const toggleAdvancedSearch = () => {
  showAdvancedSearchPanel.value = !showAdvancedSearchPanel.value
}

const handleSearch = () => {
  // 触发搜索事件
  emit('search', searchKeyword.value)
}

const handleAdvancedSearch = () => {
  // 触发高级搜索事件
  emit('advanced-search', searchForm.value)
}

const handleResetSearch = () => {
  searchKeyword.value = ''
  initSearchForm()
  emit('reset-search')
}

// 字段组件映射
const getFieldComponent = (type: string) => {
  const componentMap = {
    input: 't-input',
    select: 't-select',
    date: 't-date-picker',
    'date-range': 't-date-range-picker'
  }
  return componentMap[type as keyof typeof componentMap] || 't-input'
}

// Emits
const emit = defineEmits<{
  'select-change': [keys: (string | number)[]]
  'page-change': [pageInfo: any]
  'add': []
  'delete': [keys: (string | number)[]]
  'export': []
  'action-click': [action: any, row: any]
  'search': [keyword: string]
  'advanced-search': [form: any]
  'reset-search': []
}>()

// 事件处理
const handleSelectChange = (keys: (string | number)[]) => {
  emit('select-change', keys)
}

const handlePageChange = (pageInfo: any) => {
  emit('page-change', pageInfo)
}

const handleAdd = () => {
  emit('add')
}

const handleDelete = (keys: (string | number)[]) => {
  emit('delete', keys)
}

const handleExport = () => {
  emit('export')
}

const handleActionClick = (action: any, row: any) => {
  emit('action-click', action, row)
}

// 暴露方法给父组件
defineExpose({
  clearSearch: () => {
    searchKeyword.value = ''
    initSearchForm()
  },
  refresh: () => {
    // 触发刷新
    emit('page-change', props.pagination)
  }
})
</script>

<style lang="less" scoped>
.data-table-enhanced {
  .search-toolbar {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 16px;
    
    .t-input {
      flex: 1;
      max-width: 300px;
    }
  }
  
  .advanced-search-panel {
    background: var(--td-bg-color-container);
    border: 1px solid var(--td-border-level-1-color);
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 16px;
    
    .search-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 16px;
    }
  }
}
</style>